package test5;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: fzykd
 * Date: 2023-03-07
 * Time: 19:50
 */

//懒汉模式 完整版本
public class SingletonTest05 {
    public static void main(String[] args) {
        Singleton singleton = Singleton.getInstance();
        Singleton instance = Singleton.getInstance();
        System.out.println(singleton == instance);

    }
}


class Singleton{
    //volatile 防止指令重排序
    private static volatile Singleton instance;
    private Singleton(){}

    public static Singleton getInstance(){
        //双重if判断
        if (instance == null){
            synchronized (Singleton.class){
                if (instance == null){
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}